import com.fasterxml.jackson.databind.ObjectMapper;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.List;


/**
 * Created with IntelliJ IDEA
 * Description
 * User：chenshu
 * Date：2023-12-03
 * Time：17:33
 */
class Message {
    public String from;
    public String to;
    public String message;

    @Override
    public String toString() {
        return "Message{" +
                "from='" + from + '\'' +
                ", to='" + to + '\'' +
                ", message='" + message + '\'' +
                '}';
    }
}

@WebServlet("/message")
public class MessageServlet extends HttpServlet {
    private ObjectMapper objectMapper = new ObjectMapper();
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        //将JSON信息构造成对象
        Message message = objectMapper.readValue(req.getInputStream(), Message.class);
        //存入消息list中
        //messageList.add(message);
        save(message);
        System.out.println(message.toString());
        //发送response
        resp.setContentType("application/json; utf-8");
        resp.getWriter().write("{\"OK\" : 1}");
    }

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        resp.setContentType("application/json; charset=utf-8");
        List<Message> messageList = load();
        //把messageList转化为JSON格式
        String respJson = objectMapper.writeValueAsString(messageList);
        resp.getWriter().write(respJson);
    }

    //存储数据到Mysql
    private void save(Message message) {
        Connection connection = null;
        PreparedStatement statement = null;
        try {
            //连接数据库
            connection = DBUtil.getConnection();
            //构造sql语句
            String sql = "insert into message values(?, ?, ?)";
            statement = connection.prepareStatement(sql);
            statement.setString(1, message.from);
            statement.setString(2,message.to);
            statement.setString(3, message.message);
            //执行
            int log = statement.executeUpdate();
            if (log != 1) {
                System.out.println("插入失败");
            } else {
                System.out.println("插入成功");
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            //关闭连接
            DBUtil.close(connection, statement, null);
        }
    }

    private List<Message> load() {
        Connection connection = null;
        PreparedStatement statement = null;
        ResultSet resultSet = null;
        List<Message> messageList= new ArrayList<>();
        try {
            //建立连接
            connection = DBUtil.getConnection();
            //构造sql语句
            String sql = new String("select * from message");
            statement = connection.prepareStatement(sql);
            //执行sql语句
            resultSet = statement.executeQuery();
            while (resultSet.next()) {
                Message message = new Message();
                message.from = resultSet.getString("from");
                message.to = resultSet.getString("to");
                message.message = resultSet.getString("message");
                messageList.add(message);
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        } finally {
            DBUtil.close(connection, statement, resultSet);
        }
        return messageList;
    }
}
